package cn.swust.score.controller;


import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.swust.score.basepojo.ResultResponse;


import cn.swust.score.pojo.QueryRater;
import cn.swust.score.pojo.Rater;
import cn.swust.score.service.RaterService;
import cn.swust.score.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "评分人信息")
@RestController
@Validated
@RequestMapping("/rater")
public class RaterController {
	
	@Value("${files.path}")
	private String filesPath;
	@Autowired
	public  RaterService raterService;
	
	@ApiOperation(value="删除记录")
	@DeleteMapping(value="/del")
	public ResultResponse<Integer> delById(
	@ApiParam(required=true,value="查询记录编号") @RequestBody Integer id) {
		return new ResultResponse<Integer>( raterService.delById(id));
	}
	

	@ApiOperation(value="新增记录")
	@PostMapping(value="/add")
	@ApiParam(required = true, value = "记录值")
	// @RequestBody是作用在形参列表上，用于将前台发送过来固定格式的数据【xml 格式或者 json等】
	//封装为对应的 JavaBean 对象，封装时使用到的一个对象是系统默认配置的 HttpMessageConverter进行解析，
	//然后封装到形参上。
	//@Valid 校验Rater 里面的参数，比如不为空max，size(min,max)等
	public ResultResponse<Rater> save(@Valid  @RequestBody Rater record) {
	    if(raterService.save(record)<=0)
	        record=null;
	    else
	        record=raterService.getById(record.getId());
		return new ResultResponse<Rater>(record);
	}
	

	@ApiOperation(value = "根据ID查询记录") 
	@PutMapping(value = "/get")
	public ResultResponse<Rater> getById(
			@ApiParam(required = true, value = "查询记录编号")
			@RequestBody @Valid Integer id) {
		Rater rater = raterService.getById(id);
		return new ResultResponse<Rater>(rater);
	}

	@ApiParam(required = true , value = "记录内容")
	@PutMapping(value = "/edit") 
	public ResultResponse<Rater> editById(@Valid @RequestBody Rater record) {
		if(raterService.edit(record)<=0)
	        record=null;
	    else
	        record=raterService.getById(record.getId());
		return new ResultResponse<Rater>(record);
	}

	@ApiOperation(value = "详细列表查询") 
	@PostMapping("/list")
	public ResultResponse<PageInfo<Rater>> list
			(@ApiParam(required = false, value = "查询参数")
			@Valid @RequestBody QueryRater param) {
		 return new  ResultResponse<PageInfo<Rater>>(raterService.list(param.getPageNum(),param.getPageSize(),param));
	}

	@ApiOperation(value = "导出excel")
	@PostMapping("/excel")
	public void excel(@ApiParam(required = false, value = "查询参数") @Valid @RequestBody QueryRater param,
			HttpServletResponse response) throws IOException {
		PageInfo<Rater> listData =raterService.list(0, 0, param);

		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Rater.class, listData.getList());

		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=评分人.xls");
		workbook.write(response.getOutputStream());
	}

	@ApiOperation(value = "导入excel")
	@PostMapping("/import")
	public ResultResponse<String> importExcel(@ApiParam(required = false, value = "导入文件") @Valid MultipartFile file)
			throws IOException, Exception {
		String fileOrigName = file.getOriginalFilename();
		if (!fileOrigName.contains(".")) {
			throw new IllegalArgumentException("Lack of suffix name.");
		}
		String md5 = FileUtil.fileMd5(file.getInputStream());
		fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
		String prefix = fileOrigName.substring(fileOrigName.lastIndexOf(".") + 1);
		String pathname = FileUtil.getPath() + md5 + fileOrigName;
		String fullPath = filesPath + pathname;
		FileUtil.saveFile(file, fullPath);
		ImportParams params = new ImportParams();
		// params.setTitleRows(1);
		params.setHeadRows(1);

		List<Rater> personList = ExcelImportUtil.importExcel(file.getInputStream(), Rater.class, params);

		raterService.save(personList);
		return new ResultResponse<String>(0, "OK", file.getOriginalFilename());
	}
	
}
